import random
import uuid
import os
from datetime import datetime, timedelta
from flask import Blueprint, request, jsonify, current_app, url_for
from flask_jwt_extended import jwt_required, get_jwt_identity
import pandas as pd
from openpyxl import Workbook
from openpyxl.drawing.image import Image as XLImage
from io import BytesIO
import requests
from PIL import Image
from app.models.user import User
from app.models.cart import Cart
from app.models.product import Product
from app.models.share import CartShare
from app.models.order import Order, OrderItem
from app.utils.wx_token_manager import token_manager
from main import db
import openpyxl.styles

cart_bp = Blueprint("cart", __name__)

# 基础购物车管理API


@cart_bp.route("", methods=["GET"])
@jwt_required()
def get_cart_items():
    """获取当前用户的购物车中的所有商品"""
    userId = get_jwt_identity()
    user = User.query.get_or_404(userId)

    # if not user.is_customer():
    #    return jsonify({"error": "Only customers can view cart"}), 403

    cart_items = Cart.query.filter_by(user_id=userId).all()

    return jsonify(
        {
            "data": [item.to_dict() for item in cart_items],
            "total": len(cart_items),
            "message": "获取成功",
        }
    )


@cart_bp.route("add", methods=["POST"])
@jwt_required()
def add_to_cart():
    """添加商品到购物车（固定数量为1）"""
    userId = get_jwt_identity()
    user = User.query.get_or_404(userId)

    # 暂时注释掉，后期加上
    # if not user.is_customer():
    #    return jsonify({"error": "Only customers can add items to cart"}), 403

    data = request.get_json()
    productId = data.get("productId")
    skuCode = data.get("skuCode")  # 可选

    if not productId:
        return jsonify({"error": "Product ID is required"}), 400

    product = Product.query.get_or_404(productId)

    # 检查产品是否在电商仓库
    # if product.warehouse != "电商":
    #     return jsonify({"error": "Product not available in e-commerce warehouse"}), 400

    # 检查购物车是否已存在该商品和SKU
    existing_item = Cart.query.filter_by(
        user_id=userId, product_id=productId, sku_code=skuCode
    ).first()

    if existing_item:
        # 商品已在购物车中，返回已有的项目ID
        return jsonify(
            {
                "success": True,
                "data": {"id": existing_item.id},
                "message": "商品已在购物车中",
            }
        )
    else:
        # 添加新商品到购物车
        cart_item = Cart(
            user_id=userId,
            product_id=productId,
            sku_code=skuCode,
            quantity=1,
            selected=True,
        )
        db.session.add(cart_item)
        db.session.commit()

        return jsonify(
            {"success": True, "data": {"id": cart_item.id}, "message": "添加成功"}
        )


@cart_bp.route("/delete/<int:itemId>", methods=["DELETE"])
@jwt_required()
def remove_from_cart(itemId):
    """从购物车中删除指定商品"""
    userId = get_jwt_identity()
    user = User.query.get_or_404(userId)

    # if not user.is_customer():
    #    return jsonify({"error": "Only customers can remove items from cart"}), 403

    # 查找购物车项目
    cart_item = Cart.query.get_or_404(itemId)

    # 检查是否是当前用户的购物车项目
    if cart_item.user_id != str(userId):
        return jsonify({"error": "Unauthorized to remove this item"}), 403

    db.session.delete(cart_item)
    db.session.commit()

    return jsonify({"success": True, "message": "删除成功"})


# 额外功能API：清空购物车
@cart_bp.route("/clear", methods=["DELETE"])
@jwt_required()
def clear_cart():
    """清空当前用户的购物车"""
    userId = get_jwt_identity()
    user = User.query.get_or_404(userId)

    if not user.is_customer():
        return jsonify({"error": "Only customers can clear cart"}), 403

    Cart.query.filter_by(user_id=userId).delete()
    db.session.commit()

    return jsonify({"success": True, "message": "购物车已清空"})


# 新增功能：导出Excel
@cart_bp.route("/export-excel", methods=["POST"])
@jwt_required()
def export_excel():
    """导出购物车内选中的商品到Excel"""
    userId = get_jwt_identity()
    user = User.query.get_or_404(userId)

    data = request.get_json()
    cartItemIds = data.get("cartItemIds", [])

    if not cartItemIds:
        return jsonify({"error": "请选择要导出的商品"}), 400

    # 查询指定的购物车项目
    cart_items = []
    if cartItemIds:
        cart_items = Cart.query.filter(
            Cart.id.in_(cartItemIds), Cart.user_id == userId
        ).all()

    if not cart_items:
        return jsonify({"error": "未找到选中的商品"}), 404

    # 创建工作簿和工作表
    wb = Workbook()
    ws = wb.active
    ws.title = "商品列表"

    # 设置表头
    headers = [
        "产品编号",
        "产品名称",
        "类别",
        "预览图",
        "长度(mm)",
        "直径(mm)",
        "珍珠尺寸(mm)",
        "珍珠颜色",
        "珍珠圆度",
        "珍珠净度",
        "珍珠材质",
        "金属材质",
        "玉石材质",
        "玉石尺寸(mm)",
        "其他配件",
        "备注",
        "标价",
        "售价",
        "渠道名称",
        "渠道链接",
    ]

    # 设置表头样式
    header_font = openpyxl.styles.Font(bold=True, color="FFFFFF")
    header_fill = openpyxl.styles.PatternFill(
        start_color="4F81BD", end_color="4F81BD", fill_type="solid"
    )
    header_alignment = openpyxl.styles.Alignment(
        horizontal="center", vertical="center", wrap_text=True
    )

    # 写入表头并设置样式
    for col_num, header in enumerate(headers, 1):
        cell = ws.cell(row=1, column=col_num, value=header)
        cell.font = header_font
        cell.fill = header_fill
        cell.alignment = header_alignment
        # 设置初始列宽，根据表头内容自动调整
        col_letter = openpyxl.utils.get_column_letter(col_num)
        ws.column_dimensions[col_letter].width = max(10, len(header) * 1.5)

    # 设置初始列宽 - 预览图列需要更宽一些
    ws.column_dimensions["D"].width = 20  # 预览图列的初始宽度

    # 第一步：收集所有的云存储图片ID
    cloud_images = []
    item_images = []

    for index, item in enumerate(cart_items):
        product_data = item.product.to_dict()
        image_url = product_data.get("preview_image_url")

        if not image_url:
            item_images.append({"index": index, "url": None, "file_id": None})
            continue

        # 如果是相对路径，转换为绝对路径
        if image_url.startswith("/"):
            site_url = request.host_url.rstrip("/")
            image_url = f"{site_url}{image_url}"
            item_images.append({"index": index, "url": image_url, "file_id": None})
        # 如果是云存储图片
        elif image_url.startswith("cloud://"):
            file_id = image_url
            cloud_images.append(file_id)
            item_images.append({"index": index, "url": None, "file_id": file_id})
        # 普通HTTP图片
        else:
            item_images.append({"index": index, "url": image_url, "file_id": None})

    # 第二步：批量获取云存储图片的下载链接
    cloud_download_urls = {}
    if cloud_images:
        try:
            # 使用token_manager获取最新有效的token
            auth_token = token_manager.get_access_token()
            env_id = current_app.config.get("WX_ENV_ID", "")

            if auth_token and env_id:
                wx_api_url = f"https://api.weixin.qq.com/tcb/batchdownloadfile?access_token={auth_token}"

                # 准备请求数据 - 每50个文件ID为一组（API限制）
                file_list_groups = []
                for i in range(0, len(cloud_images), 50):
                    group = cloud_images[i : i + 50]
                    file_list_groups.append(
                        [{"fileid": file_id, "max_age": 7200} for file_id in group]
                    )

                # 对每组进行请求
                for file_list in file_list_groups:
                    file_data = {"env": env_id, "file_list": file_list}

                    wx_response = requests.post(wx_api_url, json=file_data)

                    if wx_response.status_code == 200:
                        wx_result = wx_response.json()
                        # 如果token过期，尝试刷新并重试一次
                        if (
                            wx_result.get("errcode") == 42001
                            or wx_result.get("errcode") == 40001
                        ):  # token过期错误码
                            auth_token = token_manager.get_access_token(
                                force_refresh=True
                            )
                            if auth_token:
                                wx_api_url = f"https://api.weixin.qq.com/tcb/batchdownloadfile?access_token={auth_token}"
                                wx_response = requests.post(wx_api_url, json=file_data)
                                wx_result = wx_response.json()

                        # 处理结果
                        if wx_result.get("errcode") == 0 and wx_result.get("file_list"):
                            for file_info in wx_result["file_list"]:
                                if file_info.get("status") == 0:
                                    file_id = file_info.get("fileid")
                                    download_url = file_info.get("download_url")
                                    if file_id and download_url:
                                        cloud_download_urls[file_id] = download_url
                        else:
                            current_app.logger.error(f"微信云API错误: {wx_result}")
        except Exception as e:
            current_app.logger.error(f"批量获取下载链接失败: {e}")

    # 第三步：更新每个商品的图片URL
    for item_image in item_images:
        if item_image["file_id"] and item_image["file_id"] in cloud_download_urls:
            item_image["url"] = cloud_download_urls[item_image["file_id"]]

    # 第四步：下载和处理所有图片，并填充Excel数据
    temp_files = []  # 跟踪所有临时文件

    row_num = 2
    for index, item in enumerate(cart_items):
        cart_dict = item.to_dict()
        product = item.product
        product_data = product.to_dict()

        # 查找对应的SKU
        sku_data = None
        if cart_dict.get("skuCode") and "skus" in product_data:
            for sku in product_data["skus"]:
                if sku.get("skuCode") == cart_dict.get("skuCode"):
                    sku_data = sku
                    break

        # 填充数据
        ws.cell(row=row_num, column=1, value=cart_dict.get("skuCode", ""))
        ws.cell(row=row_num, column=2, value=product_data.get("name", ""))
        ws.cell(row=row_num, column=3, value=product_data.get("category", ""))

        # 处理图片
        item_image = item_images[index]
        image_url = item_image.get("url")

        if image_url:
            try:
                # 下载图片
                response = requests.get(image_url)
                if response.status_code == 200:
                    img = Image.open(BytesIO(response.content))
                    orig_width, orig_height = img.size

                    # 设置图片尺寸限制和缩放
                    max_width = 150  # 增加最大宽度，使图片更清晰
                    max_height = 150  # 增加最大高度，使图片更清晰

                    # 缩放图片
                    if orig_width > max_width or orig_height > max_height:
                        ratio = min(max_width / orig_width, max_height / orig_height)
                        new_width = int(orig_width * ratio)
                        new_height = int(orig_height * ratio)
                        img = img.resize((new_width, new_height), Image.LANCZOS)
                    else:
                        new_width = orig_width
                        new_height = orig_height

                    # 保存图片到临时文件
                    # 确保导出目录存在
                    temp_dir = os.path.join(current_app.static_folder, "temp")
                    os.makedirs(temp_dir, exist_ok=True)
                    timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
                    random_value = str(random.randint(1000, 9999))
                    img_path = os.path.join(
                        temp_dir,
                        f"temp_{userId}_{row_num}_{timestamp}_{random_value}.png",
                    )
                    img.save(img_path)
                    temp_files.append(img_path)  # 记录临时文件路径

                    # 调整单元格大小以适应图片
                    # 列宽：1个字符约等于8.43像素(Excel默认)
                    # 行高：1点(pt)约等于1.33像素
                    col_width = max(15, new_width / 7)  # 确保最小宽度为15个字符
                    row_height = max(22, new_height * 0.75)  # 确保最小高度为22pt

                    # 设置列宽 - 只有当需要更宽时才调整列宽
                    if col_width > ws.column_dimensions["D"].width:
                        ws.column_dimensions["D"].width = col_width

                    # 设置行高
                    ws.row_dimensions[row_num].height = row_height

                    # 添加图片到Excel
                    excel_img = XLImage(img_path)

                    # 设置图片插入位置，添加小偏移使图片居中
                    cell_addr = f"D{row_num}"
                    ws.add_image(excel_img, cell_addr)
            except Exception as e:
                current_app.logger.error(f"处理图片时出错 (商品索引 {index}): {e}")

        # 设置单元格样式
        for col in range(1, 21):
            cell = ws.cell(row=row_num, column=col)
            cell.alignment = openpyxl.styles.Alignment( horizontal="center", vertical="center", )  # 垂直居中

        # 添加规格信息
        specifications = cart_dict.get("specifications", {})
        ws.cell(row=row_num, column=5, value=specifications.get("length", ""))
        ws.cell(row=row_num, column=6, value=specifications.get("diameter", ""))
        ws.cell(row=row_num, column=7, value=specifications.get("pearlSize", ""))
        ws.cell(row=row_num, column=8, value=specifications.get("pearlColor", ""))

        # 添加产品属性
        ws.cell(row=row_num, column=9, value=product_data.get("pearlRoundness", ""))
        ws.cell(row=row_num, column=10, value=product_data.get("pearlClarity", ""))
        ws.cell(row=row_num, column=11, value=product_data.get("pearlMaterial", ""))
        ws.cell(row=row_num, column=12, value=product_data.get("metalMaterial", ""))
        ws.cell(row=row_num, column=13, value=product_data.get("jadeMaterial", ""))
        ws.cell(row=row_num, column=14, value=product_data.get("jadeSize", ""))
        ws.cell(row=row_num, column=15, value=product_data.get("accessoryOthers", ""))
        ws.cell(row=row_num, column=16, value=product_data.get("remark", ""))

        # 添加价格信息
        ws.cell(row=row_num, column=17, value=cart_dict.get("listPrice", ""))
        ws.cell(row=row_num, column=18, value=cart_dict.get("salePrice", ""))

        # 渠道信息处理
        channels = product_data.get("channel", [])

        if channels and len(channels) > 0:
            # 记录起始行，用于后续合并
            start_row = row_num

            # 获取当前行高（作为基准高度）
            base_row_height = ws.row_dimensions[row_num].height / len(
                channels
            )  # 默认15如果行高未设置

            # 先添加所有渠道到各自的行
            for i, channel in enumerate(channels):
                # 如果是第一个渠道，使用当前行；否则增加行号
                if i > 0:
                    row_num += 1

                # 为每个渠道行设置计算得到的行高
                ws.row_dimensions[row_num].height = base_row_height

                # 写入渠道信息
                ws.cell(row=row_num, column=19, value=channel.get("name", ""))
                ws.cell(row=row_num, column=20, value=channel.get("link", ""))

                # 设置单元格样式
                for col in range(19, 21):
                    cell = ws.cell(row=row_num, column=col)
                    cell.alignment = openpyxl.styles.Alignment(vertical="center")

            # 如果有多个渠道，合并前面18列的单元格
            if len(channels) > 1:
                end_row = row_num
                for col in range(1, 19):
                    # 合并单元格
                    ws.merge_cells(
                        start_row=start_row,
                        start_column=col,
                        end_row=end_row,
                        end_column=col,
                    )

                    # 设置居中对齐
                    cell = ws.cell(row=start_row, column=col)
                    cell.alignment = openpyxl.styles.Alignment(
                        horizontal="center", vertical="center"
                    )

        row_num += 1

    # 第五步：保存Excel文件到微信云托管对象存储
    timestamp = datetime.now().strftime("%Y%m%d%H%M%S")

    excel_filename = f"cart_export_{userId}_{timestamp}.xlsx"

    # 添加边框样式
    thin_border = openpyxl.styles.Border(
        left=openpyxl.styles.Side(style="thin"),
        right=openpyxl.styles.Side(style="thin"),
        top=openpyxl.styles.Side(style="thin"),
        bottom=openpyxl.styles.Side(style="thin"),
    )

    # 为所有单元格添加边框
    for row in ws.iter_rows(
        min_row=1, max_row=row_num - 1, min_col=1, max_col=len(headers)
    ):
        for cell in row:
            cell.border = thin_border

    # 设置总结行 - 在最后一行添加汇总信息
    summary_row = row_num + 1
    ws.cell(row=summary_row, column=1, value="导出摘要")
    ws.cell(row=summary_row, column=1).font = openpyxl.styles.Font(bold=True)
    ws.cell(row=summary_row, column=2, value=f"总商品数: {len(cart_items)}件")
    ws.cell(
        row=summary_row,
        column=4,
        value=f"导出时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
    )

    # 冻结首行，便于滚动查看
    ws.freeze_panes = "A2"

    # 自动调整所有列宽（除了已经特别设置的D列）
    for col_num, header in enumerate(headers, 1):
        col_letter = openpyxl.utils.get_column_letter(col_num)
        if col_letter != "D":  # 跳过图片列，避免重置我们特别设置的宽度
            column_cells = [
                ws.cell(row=i, column=col_num).value for i in range(1, row_num)
            ]
            column_cells = [
                str(cell) if cell is not None else "" for cell in column_cells
            ]
            if column_cells:
                max_length = max(len(str(cell)) for cell in column_cells)
                adjusted_width = max(
                    10, min(max_length + 2, 30)
                )  # 最小10，最大30个字符宽
                ws.column_dimensions[col_letter].width = adjusted_width

    # 首先保存到临时文件
    temp_filepath = os.path.join(current_app.static_folder, excel_filename)
    wb.save(temp_filepath)
    temp_files.append(temp_filepath)  # 添加到临时文件列表

    # 1. 调用微信API获取文件上传链接
    try:
        # 获取access_token
        access_token = token_manager.get_access_token()
        if not access_token:
            current_app.logger.error(
                "Failed to get WeChat access token for file upload"
            )
            return jsonify({"error": "无法获取微信访问令牌"}), 500

        # 云环境ID
        cloud_env = current_app.config.get("WX_CLOUD_ENV")
        if not cloud_env:
            current_app.logger.error("Missing WX_CLOUD_ENV configuration")
            return jsonify({"error": "缺少云环境配置"}), 500

        # 文件存储路径
        cloud_path = f"excel/{excel_filename}"

        # 获取上传链接
        upload_url = "https://api.weixin.qq.com/tcb/uploadfile"
        request_data = {"env": cloud_env, "path": cloud_path}
        headers = {"Content-Type": "application/json"}
        response = requests.post(
            f"{upload_url}?access_token={access_token}",
            json=request_data,
            headers=headers,
        )
        upload_result = response.json()

        if upload_result.get("errcode") != 0:
            current_app.logger.error(
                f"Failed to get upload URL: {upload_result.get('errmsg')}"
            )
            return (
                jsonify({"error": f"获取上传URL失败: {upload_result.get('errmsg')}"}),
                500,
            )

        # 2. 上传文件到云存储
        with open(temp_filepath, "rb") as file_content:
            # 准备上传表单数据
            form_data = {
                "key": cloud_path,
                "Signature": upload_result.get("authorization"),
                "x-cos-security-token": upload_result.get("token"),
                "x-cos-meta-fileid": upload_result.get("cos_file_id"),
            }
            files = {
                "file": (
                    cloud_path,
                    file_content,
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                )
            }

            # 发送上传请求
            upload_response = requests.post(
                upload_result.get("url"), data=form_data, files=files
            )

            if (
                upload_response.status_code != 204
                and upload_response.status_code != 200
            ):
                current_app.logger.error(
                    f"Failed to upload file: HTTP {upload_response.status_code}"
                )
                return jsonify({"error": "文件上传失败"}), 500

        # 文件上传成功，返回文件ID和下载链接
        file_id = upload_result.get("file_id")

        # 3. 删除所有临时文件
        for temp_file in temp_files:
            try:
                if os.path.exists(temp_file):
                    os.remove(temp_file)
            except Exception as e:
                current_app.logger.warning(
                    f"Failed to delete temp file {temp_file}: {str(e)}"
                )

        return jsonify(
            {
                "code": 200,
                "message": "导出成功",
                "data": {"fileID": file_id, "fileName": excel_filename},
            }
        )

    except Exception as e:
        current_app.logger.error(f"Failed to upload file to cloud storage: {str(e)}")

        # 出错时仍然返回本地文件
        file_url = url_for("static", filename=excel_filename, _external=True)

        # 删除所有临时文件，但保留导出的Excel
        for temp_file in temp_files:
            if temp_file != os.path.join(current_app.static_folder, excel_filename):
                try:
                    if os.path.exists(temp_file):
                        os.remove(temp_file)
                except Exception as e:
                    current_app.logger.warning(
                        f"Failed to delete temp file {temp_file}: {str(e)}"
                    )

        return jsonify(
            {
                "code": 200,
                "message": "导出成功但云存储上传失败，已保存到本地",
                "data": {"fileUrl": file_url, "fileName": excel_filename},
            }
        )


# 新增功能：分享购物车
@cart_bp.route("/share", methods=["POST"])
@jwt_required()
def share_cart():
    """生成购物车分享链接"""
    userId = get_jwt_identity()
    user = User.query.get_or_404(userId)

    data = request.get_json()
    cartItemIds = data.get("cartItemIds", [])

    if not cartItemIds:
        return jsonify({"error": "请选择要分享的商品"}), 400

    # 检查所有ID是否存在并属于当前用户
    cart_items = Cart.query.filter(
        Cart.id.in_(cartItemIds), Cart.user_id == userId
    ).all()

    if len(cart_items) != len(cartItemIds):
        return jsonify({"error": "部分或全部选中的商品不存在"}), 404

    # 生成唯一分享码
    shareId = str(uuid.uuid4())[:8]

    # 设置过期时间（7天后）
    expiresAt = datetime.now() + timedelta(days=7)

    # 创建分享记录
    cartShare = CartShare(
        share_code=shareId,
        user_id=userId,
        cart_item_ids=cartItemIds,
        expires_at=expiresAt,
    )
    db.session.add(cartShare)
    db.session.commit()

    return jsonify({"code": 200, "message": "Success", "data": {"shareId": shareId}})


# 获取分享的购物车
@cart_bp.route("/shared/<string:shareId>", methods=["GET"])
def get_shared_cart(shareId):
    """获取分享的购物车内容"""
    # 查找分享记录
    cartShare = CartShare.query.filter_by(
        share_code=shareId, is_active=True
    ).first_or_404()

    # 检查是否过期
    if cartShare.expires_at and cartShare.expires_at < datetime.now():
        return jsonify({"error": "分享链接已过期"}), 410

    # 获取购物车项目ID列表
    cartItemIds = cartShare.get_cart_item_ids()

    # 查询对应的购物车项目
    cart_items = Cart.query.filter(Cart.id.in_(cartItemIds)).all()

    # 返回购物车内容
    return jsonify(
        {
            "code": 200,
            "message": "Success",
            "data": {
                "shareInfo": cartShare.to_dict(),
                "items": [item.to_dict() for item in cart_items],
            },
        }
    )


# 新增功能：下单
@cart_bp.route("/place-order", methods=["POST"])
@jwt_required()
def place_order():
    """将购物车中的商品转化为订单"""
    userId = get_jwt_identity()
    user = User.query.get_or_404(userId)

    data = request.get_json()
    cartItemIds = data.get("cartItemIds", [])
    remarks = data.get("remarks", "")

    if not cartItemIds:
        return jsonify({"error": "请选择要下单的商品"}), 400

    # 查询指定的购物车项目
    cart_items = Cart.query.filter(
        Cart.id.in_(cartItemIds), Cart.user_id == userId
    ).all()

    if not cart_items:
        return jsonify({"error": "未找到选中的商品"}), 404

    # 生成唯一的订单编号
    max_attempts = 5  # 最大尝试次数
    attempt = 0
    while attempt < max_attempts:
        order_number = (
            f"ORD{datetime.now().strftime('%Y%m%d%H%M%S')}{random.randint(1000, 9999)}"
        )
        # 检查订单号是否已存在
        if not Order.query.filter_by(order_number=order_number).first():
            break
        attempt += 1
        if attempt == max_attempts:
            return jsonify({"error": "生成订单号失败，请稍后重试"}), 500

    # 创建订单
    new_order = Order(order_number=order_number, user_id=userId, remarks=remarks)
    db.session.add(new_order)
    db.session.flush()  # 获取自增ID

    # 创建订单项目
    total_items = 0
    products_info = []
    for cart_item in cart_items:
        cart_dict = cart_item.to_dict()
        price = cart_dict.get("salePrice", 0)

        # 获取商品信息，用于通知
        product = Product.query.get(cart_item.product_id)
        if product:
            products_info.append({"name": product.name, "quantity": cart_item.quantity})
            total_items += cart_item.quantity

        order_item = OrderItem(
            order_id=new_order.id,
            product_id=cart_item.product_id,
            sku_code=cart_item.sku_code,
            quantity=cart_item.quantity,
            price=price,
        )
        db.session.add(order_item)

        # 从购物车中移除该项目
        db.session.delete(cart_item)

    db.session.commit()

    # 发送订阅消息通知给员工和管理员
    # 这里有点问题，非政务、医疗领域智能使用一次性订阅消息，不能满足客户的需求，先不管。
    try:
        # 获取客户信息
        customer_name = user.username if user else "未知用户"

        # 获取所有员工和管理员
        staff_users = User.query.filter(User.role.in_(["admin", "employee"])).all()

        if staff_users:
            # 生成商品摘要信息
            product_summary = f"{total_items}件商品"
            if products_info and len(products_info) > 0:
                first_product = products_info[0]["name"]
                if len(products_info) > 1:
                    product_summary = f"{first_product}等{total_items}件商品"
                else:
                    product_summary = f"{first_product} {total_items}件"

            # 获取access token
            access_token = token_manager.get_access_token()
            if not access_token:
                current_app.logger.error(
                    "Failed to get WeChat access token for order notification"
                )
            else:
                # 订阅消息模板ID
                template_id = "h_x2LZhH_auJPr_CksMrjTJCmEK-_oiUaC3-vPGaUmc"

                # 准备发送的数据
                now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

                # 为每个员工发送订阅消息
                for staff in staff_users:
                    # 如果没有openid，跳过
                    if not staff.openid:
                        continue

                    # 发送订阅消息
                    send_url = f"https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={access_token}"
                    message_data = {
                        "touser": staff.openid,
                        "template_id": template_id,
                        "page": f"pages/order/detail?orderId={order_number}",
                        "data": {
                            "character_string1": {"value": order_number},  # 订单编号
                            "time2": {"value": now},  # 确认时间
                            "thing9": {"value": f"订单号: {customer_name}"},  # 买家信息
                            "thing17": {"value": remarks},  # 备注
                        },
                    }

                    try:
                        response = requests.post(send_url, json=message_data)
                        result = response.json()

                        if result.get("errcode") != 0:
                            current_app.logger.warning(
                                f"Failed to send order notification to staff {staff.id}. Error: {result.get('errmsg')}"
                            )
                    except Exception as e:
                        current_app.logger.error(
                            f"Error sending subscription message: {str(e)}"
                        )
    except Exception as e:
        # 通知发送失败不影响下单流程
        current_app.logger.error(f"Failed to send order notifications: {str(e)}")

    return jsonify(
        {"code": 200, "message": "下单成功", "data": {"orderId": order_number}}
    )
